package com.szpxt.listener;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.dom4j.DocumentException;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.szpxt.model.Organization;
import com.szpxt.model.Role;
import com.szpxt.model.User;
import com.szpxt.service.OrganizationService;
import com.szpxt.service.PrivilegeService;
import com.szpxt.service.RoleService;
import com.szpxt.service.UserService;

public class StartListener implements ServletContextListener {

	@Override
	public void contextDestroyed(ServletContextEvent event) {}

	@Override
	public void contextInitialized(ServletContextEvent event) {
		WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());
		PrivilegeService privilegeService = (PrivilegeService)context.getBean("privilegeService");
		RoleService roleService = (RoleService)context.getBean("roleService");
		OrganizationService organizationService = (OrganizationService)context.getBean("organizationService");
		UserService userService = (UserService)context.getBean("userService");
		
		try {		//初始化权限
			privilegeService.inititalize();
		} 
		catch (DocumentException e) {
			e.printStackTrace();
		}
		
		if(roleService.getAll().size() == 0) {									//数据库初始化
			Role role = new Role();												//超级管理员角色
			role.setName("超级管理员");
			role.setListPrivilege(privilegeService.getAll());
			roleService.saveOrUpdate(role);
			
			Organization organization = new Organization();						//人民银行
			organization.setName("人民银行");
			organizationService.saveOrUpdate(organization);
			
			Map<String, String> mapUser = new HashMap<String, String>();		//超级用户
			mapUser.put("name", "钟戈");
			mapUser.put("password", "888888");
			mapUser.put("organizationId", organization.getId() + "");
			mapUser.put("roleId", role.getId() + "");
			try {
				userService.saveOrUpdate(mapUser);
			} 
			catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			} 
			catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			
		}
		
		
	}
	
}